package com.miao.im.support.tester;

import cn.hutool.core.lang.SimpleCache;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.util.List;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/7/14 22:05
 * @Description:
 */
public class TestBeanJsonModifier extends BeanSerializerModifier {
    private static SimpleCache<Class<? extends IConverter>, JsonSerializer<Object>> cache = new SimpleCache<>();

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        // 循环所有的beanPropertyWriter
        for (BeanPropertyWriter writer : beanProperties) {
            TextDisplay annotation = writer.getAnnotation(TextDisplay.class);
            if (annotation != null) {
                writer.assignSerializer(setAndGet(annotation.value(), writer.getName()));
            }
            // 判断字段的类型，如果是array，list，set则注册nullSerializer
//            if (isArrayType(writer)) {
//                //给writer注册一个自己的nullSerializer
//                writer.assignNullSerializer(arrayJsonSerializer);
//            } else if (isDate(writer)) {
//                writer.assignNullSerializer(dateJsonSerializer);
//            } else if (isNumber(writer)) {
//                writer.assignNullSerializer(numberJsonSerializer);
//            } else if (isStr(writer)) {
//                writer.assignNullSerializer(strJsonSerializer);
//            }
        }
        return beanProperties;
    }

    private JsonSerializer<Object> setAndGet(Class<? extends IConverter> converter, String fieldName) {
        JsonSerializer<Object> jsonSerializer = cache.get(converter);
        if (jsonSerializer != null) {
            return jsonSerializer;
        }
        TestJsonSerializer newSerializer = new TestJsonSerializer(converter, fieldName);
        return cache.put(converter, new TestJsonSerializer(converter, fieldName));
    }
}
